package com.zxtech.zzm.zxmonitorsocket.thread

import com.zxtech.zzm.core.util.LoggerUtil
import com.zxtech.zzm.zxmonitorsocket.ZXMonitorSocketService
import com.zxtech.zzm.zxmonitorsocket.resolver.HeartBeatResolver
import com.zxtech.zzm.zxmonitorsocket.util.SocketLoggerUtil
import java.text.SimpleDateFormat
import java.util.logging.SimpleFormatter

/**
 * Created by zheming.zou on 2017/2/9.
 * 需要同时检测实时信号Socket,广告Socket和守护进程是否正常运行，异常重启
 */
class MonitorThread : Thread() {
  @Volatile private var stopflag = true //true 线程停止， false线程继续
  fun setStopFlag(stopFlag: Boolean) {
    stopflag = stopFlag
  }
  val sdf = SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒")
  override fun run() {
    this.name = "zxmonitor_socket_monitor"
    SocketLoggerUtil.logSocket("线程" + this.id + "检测线程开始")
    stopflag = false
    while (!stopflag) {
      try {
        sleep((23 * 1000).toLong())
      } catch (e: InterruptedException) {
        e.printStackTrace()
      }
      SocketLoggerUtil.logSocket(
          """
  线程${this.id}Monitor线程正在检测心跳
  现在：${sdf.format(System.currentTimeMillis())}
  距离上次收到心跳回包${(System.currentTimeMillis() - HeartBeatResolver.heartBeatReceivedTime) / 1000}秒
  """.trimIndent(), LoggerUtil.LOGGERUTIL_WARNING
      )
      if (System.currentTimeMillis() - HeartBeatResolver.heartBeatReceivedTime > 30 * 1000) {
        //心跳超时，重连
        SocketLoggerUtil.logSocket("线程" + this.id + "monitor线程重连", LoggerUtil.LOGGERUTIL_ERROR)
        ZXMonitorSocketService.reconnect()
      }
    }
    SocketLoggerUtil.logSocket("线程" + this.id + "检测线程终止")
  }
}